#include "qsfmlcanvas.h"
#ifdef Q_WS_X11
# include <Qt/qx11info_x11.h>
# include <X11/Xlib.h>
#endif

QSFMLCanvas::QSFMLCanvas(QWidget *parent) : QWidget(parent)
{
    setAttribute(Qt::WA_PaintOnScreen);
    setAttribute(Qt::WA_NoSystemBackground);
    setAttribute(Qt::WA_OpaquePaintEvent);
    setFocusPolicy(Qt::StrongFocus);
    _timer.setInterval(50);
}

QSFMLCanvas::~QSFMLCanvas()
{
}

QPaintEngine* QSFMLCanvas::paintEngine() const
{
    return (0);
}

void QSFMLCanvas::showEvent(QShowEvent *)
{
    if (!_initialized)
    {
#ifdef Q_WS_X11
        XFlush(QX11Info::display());
#endif
        Create(winId());
        OnInit();
        connect(&_timer, SIGNAL(timeout()), this, SLOT(repaint()));
        _timer.start();
        _initialized = true;
    }
}

void QSFMLCanvas::resizeEvent(QResizeEvent* event)
{
    QSize size = event->size();

    sf::Window::SetSize(size.width(), size.height());
}

void QSFMLCanvas::paintEvent(QPaintEvent *)
{
    OnUpdate();
    Display();
}

void QSFMLCanvas::OnUpdate()
{
}

void QSFMLCanvas::OnInit()
{
}

void QSFMLCanvas::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::RightButton)
    {
        _movingLastPos.x = event->pos().x();
        _movingLastPos.y = event->pos().y();
        _isMoving        = true;
    }
}

void QSFMLCanvas::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::RightButton)
    {
        _isMoving = false;
    }
}

void QSFMLCanvas::mouseMoveEvent(QMouseEvent* event)
{
    if (_isMoving)
    {
        sf::Vector2f newPos(event->pos().x(), event->pos().y());
        sf::View     view    = this->GetView();
        sf::Vector2f viewPos = view.GetCenter();
        sf::Vector2f size    = view.GetSize();

        viewPos.x += _movingLastPos.x - newPos.x;
        viewPos.y += _movingLastPos.y - newPos.y;
        _movingLastPos = newPos;

        size.x /= 2;
        size.y /= 2;
        if (_maxSize.x > 0)
        {
            if (viewPos.x - size.x > _maxSize.x)
              viewPos.x = _maxSize.x - size.x;
            else if (viewPos.x - size.x < 0)
              viewPos.x = size.x;
        }
        if (_maxSize.y > 0)
        {
            if (viewPos.y - size.y > _maxSize.y)
              viewPos.y = _maxSize.y - size.y;
            else if (viewPos.y - size.y < 0)
              viewPos.y = size.y;
        }

        view.SetCenter(viewPos);
        this->SetView(view);
    }
}

QPoint QSFMLCanvas::GetAbsolutePosFromClick(const QMouseEvent* event) const
{
    sf::Vector2f size(GetWidth(), GetHeight());
    sf::Vector2f viewPos = GetView().GetCenter();
    QPoint       clickPos;

    viewPos.x -= size.x / 2;
    viewPos.y -= size.y / 2;
    clickPos.setX(event->pos().x() + viewPos.x);
    clickPos.setY(event->pos().y() + viewPos.y);
    return (clickPos);
}
